package com.lr.springbootdemo.util;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

/**
 * json 工具类.
 * Created by li.rui on 2016/4/19.
 */
public class JsonUtil {
    private static Logger logger = LoggerFactory.getLogger(JsonUtil.class);
    private static ObjectMapper mapper;
    private static ObjectMapper getMapper(){
        if(mapper == null){
            mapper = new ObjectMapper();
            mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
            mapper.getVisibilityChecker().withFieldVisibility(JsonAutoDetect.Visibility.ANY);
            mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
        }
        return mapper;
    }
    /**
     * object convert to json string
     * @param obj obj
     * @return json String
     */
    public static String object2String(Object obj) {
        try {
            return getMapper().writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            logger.error(e.getMessage(),e);
        }
        return null;
    }

    /**
     * object convert to json string
     * @param jsonStr jsonStr
     * @param clazz clazz
     * @return <T> Object
     */
    public static <T> T string2Object(String jsonStr, Class<T> clazz) {
        try {
            return getMapper().readValue(jsonStr, clazz);
        } catch (IOException e) {
            logger.error(e.getMessage(),e);
        }
        return null;
    }
}
